﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;

using CronusModel;
using Cronus.ViewModel.Data;

namespace Cronus.ViewModel
{
    /// <summary>
    /// Returns an observable collection of tasks associated with the data model.
    /// </summary>
    public class ObservableTasks : ObservableCollection<Task>
    {
        //*** Constants ***//
        //*** Static ***//
        //*** Member Variables ***//
        private string _ProjectName;

        //*** Properties ***//

        //*** Constructors ***//
        public ObservableTasks()
        {
            InitializeCollection(null, null);
        }

        //*** Abstract Methods ***//
        //*** Methods ***//
        /// <summary>
        /// Refresh the current collection.  Requeries the dataset.
        /// </summary>
        public void RefreshCollection(DataModel aDataModel)
        {
            // Force a requery on the same parameters.
            InitializeCollection(aDataModel, _ProjectName);
        }

        /// <summary>
        /// Clears the current collection, queries the data model and sorts all of the associated
        /// tasks by the name of the task.  Adds all of the returned tasks back to the colection.
        /// </summary>
        /// <param name="strProjectName">Name of the project to query on.  If empty, queries on all.</param>
        private void InitializeCollection(DataModel aDataModel, string strProjectName)
        {
            _ProjectName = strProjectName;

            // First, clear all of the items in this collection
            ClearItems();

            // Query the data model for all of the tasks associated with the data model and
            // sort them by name.
            //QueryProjectInformation aProjectQuery = new QueryProjectInformation(_DataModel);
            //IEnumerable<CronusData.TasksRow> allTasks = aProjectQuery.GetTasksAssociatedWithProject("");
            //IEnumerable<CronusData.TasksRow> allSortedTasks = null;
            //allSortedTasks = from aTask in allTasks
            //                 orderby aTask.Name ascending // Sort by name
            //                 select aTask;

            if (null != aDataModel)
            {
                // Select all of the tasks in the dataset and sort by name.
                var allResults = from aTask in aDataModel.TasksTable
                                 orderby aTask.Name ascending
                                 select aTask;

                // Add each of the tasks to this collection
                foreach (CronusData.TasksRow aRow in allResults)
                {
                    Add(new Task(aRow));
                }
            }
        }
    }
}
